package me.liangdi.spring.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Rest 调用结果工具类
 * {
 *     success:true|false
 *     value:object
 *     list:list
 *     code:code
 *     message:message
 * }
 * Created by liangdi on 1/5/16.
 */
public class Result {
    public static final String FIELD_SUCCESS = "success";
    public static final String FIELD_VALUE = "value";
    public static final String FIELD_LIST = "list";
    public static final String FIELD_MESSAGE = "message";
    public static final String FIELD_CODE = "code";

    public static final int CODE_SUCCESS = 0;
    public static final Object TRUE = Boolean.TRUE;
    public static final Object FALSE = Boolean.FALSE;

    /**
     * 工具方法 备用
     * @return
     */
    private static Map<String,Object> getHashMap(){
        Map<String,Object> ret = new HashMap<>();
        return ret;
    }

    /**
     * 返回正确的结果
     * @param obj
     * @return
     */
    public static Map<String,Object> success(Object obj){
        Map<String,Object> ret = getHashMap();
        ret.put(FIELD_SUCCESS,TRUE);
        /**
         * 处理list或者value
         */
        if(obj instanceof List) {
            ret.put(FIELD_LIST,obj);
        } else {
            ret.put(FIELD_VALUE,obj);
        }

        ret.put(FIELD_CODE,CODE_SUCCESS);
        return ret;
    }

    /**
     * 返回失败结果
     * TODO 重构
     * @return
     */
    public static Map<String,Object> fail() {
        Map<String, Object> map = getHashMap();
        map.put(FIELD_SUCCESS,FALSE);
        return map;
    }
    public static Map<String,Object> fail(int code) {
        Map<String, Object> map = getHashMap();
        map.put(FIELD_SUCCESS,FALSE);
        map.put(FIELD_CODE,code);
        return map;
    }
    public static Map<String,Object> fail(int code,String message) {
        Map<String, Object> map = getHashMap();
        map.put(FIELD_SUCCESS,FALSE);
        map.put(FIELD_CODE,code);
        map.put(FIELD_MESSAGE,message);
        return map;
    }

}
